<template>
  <section class="brand-container">
    <div class="title">热门品牌</div>
    <ul class="selectbrand-wrapper">
      <template v-for="(selectItem, selectIndex) in slectedbrandList">
        <router-link tag="li"
          :to="{name: 'ModelList', query: {searchType: 1, page: 1, keyword: selectItem.name}}"
         class="select-item" :key="selectIndex">
          <img class="brand_img" :src="prefixImg + selectItem.image" :title="selectItem.name"/>
          <p class="brand_name">{{selectItem.name}}</p>
        </router-link>
      </template>
      
    </ul>
    <!--  :class="{'fixed-alph': isAlphFixed, 'alphabets': true }" -->
    <div ref="alphabetsRef" class="alphabets">
      <ul class="alpha-block title">
        <span class="left pad-rt20">按字母选择</span>
        <!-- <li class="alpha-li">
          <a class="alpha-item">#</a>
        </li> -->
        <li class="alpha-li" v-for="(alpha, index) in alphabets" :key="index">
          <a class="alpha-item" @click="handleClickBrand(alpha)">{{alpha}}</a>
        </li>
      </ul>
    </div>
    <div class="brands">
      <div class="brand-line" :ref="item.letter" v-for="(item, letterIndex) in letterList" :key="letterIndex">
        <div class="alphabet"  :data-index="letterIndex">{{item.letter}}</div>
        <ul class="brand-list">
          <!--:to="{name: 'SearchPage', query: {page: 1, keyword: brandItem.name, r: randomDigit()}}" -->
          <router-link tag="li"
            :to="{name: 'ModelList', query: {searchType: 1, page: 1, keyword: brandItem.name, r: randomDigit()}}"
            class="brand-item" v-for="(brandItem, brandIndex) in item.data" :key="brandIndex">
            <div class="img-box">
              <img :src="prefixImg + brandItem.img" :title="brandItem.name">
            </div>
            <div class="brand-name">{{brandItem.name}}</div>
          </router-link>
        </ul>
      </div>
    </div>
  </section>
</template>

<script>
import { getBrandListByKeyword, getSelectedBrand } from '@/service/get-data'
import { isChinese, isChar, randomDigit } from '@/tool/tool'
import { prefixImg } from '@/tool/index'
export default {
  name: 'brandCenter',
  data () {
    return {
      slectedbrandList: [], // 精选品牌
      isAlphFixed: false,
      brandTop: {},
      letter: '', // 当前的letter
      prefixImg,
      bMove: false,
      showLetter: false,
      defalutLetter: 'B',
      redColorIndex: 0,
      letterList: [],
      brandList: [],
      ticking: false
    }
  },
  computed: {
    alphabets () {
      return this.filterIndex(this.letterList)
    }
  },
  methods: {
    randomDigit () {
      randomDigit()
    },
    handleClickBrand (alpha) {
      this.letter = alpha
      const element = this.$refs[alpha][0]
      // {behavior: 'smooth', block: 'center'}
      element.scrollIntoView({behavior: 'smooth', block: 'start'})
    },
    // 通过关键字获取品牌列表
    async fetchBrandList () {
      let res = await getBrandListByKeyword('', '', '', '')
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.brandList = res.data.data
        this.letterList = this.pySort(this.brandList)
        // console.log(this.letterList)
        // this.$nextTick(() => {
        //   setTimeout(this.setLisIndexPos, 60)
        // })
      }
    },
    pySort (arr, empty) {
      // debugger
      // var $this = this
      if (!String.prototype.localeCompare) return null
      var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
      var zh = '阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫咋'.split('')
      var arrList = []

      for (let m = 0; m < arr.length; m++) {
        var obj = {
          name: arr[m]['name'],
          img: arr[m]['image'],
          id: arr[m]['id']
        }
        arrList.push(obj)
      }
      var result = []
      var curr
      for (var i = 0; i < letters.length; i++) {
        // debugger
        curr = { letter: letters[i], data: [] }
        if (i !== 26) {
          for (var j = 0; j < arrList.length; j++) {
            var initial = arrList[j]['name'].charAt(0) // 截取第一个字符
            if (zh[i] !== '*' && isChinese(initial)) {
              // 判断是否是无汉字,是否是中文
              if (initial.localeCompare(zh[i], 'zh') >= 0 && (!zh[i + 1] || initial.localeCompare(zh[i + 1], 'zh') < 0)) {
                // 判断中文字符在哪一个类别
                curr.data.push(arrList[j])
              }
            } else if (
              arrList[j]['name'].charAt(0) === letters[i] ||
              arrList[j]['name'].charAt(0) === letters[i].toLowerCase()
            ) {
              // 首字符是英文的
              curr.data.push(arrList[j])
            }
          }
        } else {
          for (var k = 0; k < arrList.length; k++) {
            var ini = arrList[k]['name'].charAt(0) // 截取第一个字符
            if (isChar(ini) && isChinese(ini)) {
              curr.data.push(arrList[k])
            }
          }
        }
        if (empty || curr.data.length) {
          result.push(curr)
          // curr.data.sort(function(a,b){
          //    return b.localeCompare(a);       //排序,英文排序,汉字排在英文后面
          // });
        }
      }
      return result
    },
    filterIndex (data) {
      var resultIndex = []
      for (var i = 0; i < data.length; i++) {
        if (data[i].letter) {
          resultIndex.push(data[i].letter)
        }
      }
      return resultIndex
    },
    setScroll (letter) {
      var el = document.documentElement ? document.documentElement : document.body
      var aP = document.getElementsByClassName('tit-line')
      var aLi = document.getElementById('list_index').getElementsByTagName('li')
      for (var i = 0; i < aP.length; i++) {
        if (aP[i].innerText.toLocaleString() === letter.toLocaleString()) {
          el.scrollTop = aP[i].offsetParent.offsetTop - 46
          for (var j = 0; j < aLi.length; j++) {
            if (aLi[j].getAttribute('data-index') - 0 === i) {
              this.redColorIndex = j
            }
          }
        }
      }
    },
    showBigLetter (letter) {
      this.showLetter = true
      if (this.showLetter) {
        this.letter = letter
        setTimeout(() => {
          this.showLetter = false
        }, 1000)
      }
    },
    // 精选品牌
    async fetchSelectedBrandList () {
      let res = await getSelectedBrand()
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.slectedbrandList = res.data.data
      }
    }
  },
  mounted () {
    this.fetchSelectedBrandList()
    window.setTimeout(() => {
      this.fetchBrandList()
    }, 100)
  },
  watch: {
    // 监听letter，当letter发生变化时触发

  }
}
</script>

<style lang="scss" scoped>
.brand-container{
  width: 1190px;
  margin: 0 auto 30px;
  .title{
    color: #333;
    font-size: 18px;
    padding: 25px 0 16px;
    overflow: hidden;
  }
  .selectbrand-wrapper{
    position: relative;
    overflow: hidden;
    .select-item{
      cursor: pointer;
      float: left;
      width: 230px;
      height: 120px;
      padding: 30px 0 20px;
      border: 1px solid #eee;
      background: white;
      text-align: center;
      margin-right: 10px;
      margin-bottom: 10px;
      box-sizing: border-box;
      &:nth-child(5n){
        margin-right: 0;
      }
      .brand_img{
        height: 40px;
      }
      .brand_name{
        margin-top: 15px;
        font-size: 14px;
        color: #333333;
      }
    }
  }
}
.alphabets{
  margin-bottom: 15px;
  .alpha-li {
    float: left;
    cursor: pointer;
    text-align: center;
    width: 30px;
    &::first-child{
      padding-left: 20px;
    }
    .alpha-item{
       color: #0368CD;
    }
  }
}
.pad-rt20{
  padding-right: 20px;
}
.fixed-alph{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  width: auto;
  z-index: 5;
  background: #fff;
  height: auto;
  box-shadow: 0px 0px 6px 0px rgba(254,196,63,0.5);
  padding-bottom: 10px;
  text-align: center;
  padding: 20px 0;
  .alpha-block{
    width: 1250px;
    margin: 0 auto;
  }
}
.brand-line{
  padding: 20px;
  overflow: hidden;
  background: #fff;
  margin-bottom: 10px;
  .alphabet{
    width: 80px;
    float: left;
    font-size: 18px;
    color: #333333;
    padding: 10px;
  }
  .brand-list{
    overflow: hidden;
    margin-left: 100px;
  }
  .brand-item{
    float: left;
    padding-top: 20px;
    cursor: pointer;
    position: relative;
    text-align: center;
    border: 1px solid rgba(238,238,238,1);
    margin: 0 8px 10px 0;
    width: 166px;
    height: 86px;
    box-sizing: border-box;
    .img-box{
      width: 125px;
      height: 30px;
      overflow: hidden;
      margin: 0 auto;
      img{
        // width: 100%;
        height: 100%;
      }
    }
  }
  .brand-name{
    font-size: 12px;
    text-align: center;
    margin-top: 11px;
    line-height: 14px;
    color: #333;
  }
}
</style>
